package org.example;

import bean.DB;
import bean.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/loginServlet") // URL 映射
public class loginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 重定向到登录页面
        response.sendRedirect("login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单提交的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        DB db = new DB();
        try {
            if (validateUserAndPass(db, username, password)) {
                // 用户名和密码验证成功，获取用户信息
                String userId = getUserId(db, username);
                String avatarPath = getUserAvatar(db, userId);  // 获取头像路径

                // 登录成功，将用户名、头像路径和用户ID存储到 session 中
                request.getSession().setAttribute("username", username);   // 设置用户名到 session
                request.getSession().setAttribute("user_avatar", avatarPath);  // 设置头像路径到 session
                request.getSession().setAttribute("userId", userId);  // 设置用户ID到 session

                // 重定向到 userinfo.jsp 页面
                response.sendRedirect("userinfo.jsp"); // 重定向到 userinfo.jsp
            } else if (!validateUser(db, username)) {
                // 用户名不存在
                ResponseUtils.sendResponse(response, "登录失败,用户名不存在", "login.jsp");
            } else {
                // 密码错误
                ResponseUtils.sendResponse(response, "登录失败,密码错误", "login.jsp");
            }
        } finally {
            db.close(); // 确保资源释放
        }
    }

    // 验证用户名是否存在
    public static boolean validateUser(DB db, String username) {
        String sql = "SELECT * FROM users WHERE username = ?";
        ResultSet rs = null;

        try (PreparedStatement pstmt = db.createConn().prepareStatement(sql)) {
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();
            return rs.next(); // 如果用户名存在，返回 true
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 获取用户头像路径
    private String getUserAvatar(DB db, String userId) {
        String sql = "SELECT user_avatar FROM users WHERE id = ?";
        ResultSet rs = null;
        try (PreparedStatement pstmt = db.createConn().prepareStatement(sql)) {
            pstmt.setString(1, userId);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getString("user_avatar"); // 返回头像路径
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return "image/public/defaultAvatar.jpg"; // 默认头像路径
    }

    // 验证用户名和密码
    public static boolean validateUserAndPass(DB db, String username, String password) {
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        ResultSet rs = null;

        try (PreparedStatement pstmt = db.createConn().prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            return rs.next(); // 如果查询到结果，表示验证通过
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 获取用户 ID
    public String getUserId(DB db, String username) {
        String sql = "SELECT id FROM users WHERE username = ?";
        ResultSet rs = null;

        try (PreparedStatement pstmt = db.createConn().prepareStatement(sql)) {
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                return rs.getString("id");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new ServletException("加载数据库驱动失败", e);
        }
    }
}
